﻿using System;
using System.Collections.Generic;
using System.Management;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using System.DirectoryServices;
using System.Collections;
using System.Web.Security;

namespace ywxt.Common
{
    /// <summary>
    /// 公共静态类，执行一些公共函数
    /// </summary>
    public static class Common
    {
        #region 生成自定义的GUID值
        /// <summary>
        /// 生成自定义的GUID值
        /// </summary>
        /// <returns></returns>
        public static Guid NewMyGuid()
        {
            string s = DateTime.Now.Ticks.ToString("x") + Guid.NewGuid().ToString("N");
            return new Guid(s.Substring(0, 32));
        }
        #endregion

        #region 生成GUID类型的数据ID值（字符串类型）
        /// <summary>
        /// 生成GUID类型的数据ID值（字符串类型）
        /// </summary>
        /// <returns></returns>
        public static string NewID()
        {
            /*
            1、Guid.NewGuid().ToString("N") 结果为：
                  38bddf48f43c48588e0d78761eaa1ce6

            2、Guid.NewGuid().ToString("D") 结果为： 
                  57d99d89-caab-482a-a0e9-a0a803eed3ba

            3、Guid.NewGuid().ToString("B") 结果为：
                 {09f140d5-af72-44ba-a763-c861304b46f8}

            4、Guid.NewGuid().ToString("P") 结果为：
                 (778406c2-efff-4262-ab03-70a77d09c2b5)

            可见默认的为第2种效果
             */

            return NewMyGuid().ToString("N");
        }
        #endregion

        #region 生成GUID类型的数据ID值（GUID类型）
        /// <summary>
        /// 生成GUID类型的数据ID值（GUID类型）
        /// </summary>
        /// <returns></returns>
        public static Guid NewGuid()
        {
            return NewMyGuid();
        }
        #endregion

        #region 对字符串进项Base64编码
        public static string EncodeBase64(string value)
        {
            try
            {
                if (value == null || value == "")
                {
                    return "";
                }
                byte[] bytes = Encoding.UTF8.GetBytes(value);
                return Convert.ToBase64String(bytes);
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 对字符串进项Base64解码
        public static string DecodeBase64(string value)
        {
            try
            {
                if (value == null || value == "")
                {
                    return "";
                }
                byte[] bytes = Convert.FromBase64String(value);
                return Encoding.UTF8.GetString(bytes);
            }
            catch
            {
                return "";
            }
        }
        #endregion

        #region 写操作系统日志
        /// <summary>
        /// 写操作系统日志
        /// </summary>
        /// <param name="_str_msg"></param>
        public static void writeLog(string _str_msg)
        {
            if (!EventLog.SourceExists(CONST_LOG_SOURCE))
            {
                EventLog.CreateEventSource(CONST_LOG_SOURCE, CONST_LOG_SOURCE_NAME);
            }

            using (EventLog myLog = new EventLog())
            {
                myLog.Source = CONST_LOG_SOURCE_NAME;
                myLog.WriteEntry(_str_msg);
            }
        }

        /// <summary>
        /// 写事件日志——消息
        /// </summary>
        /// <param name="_str_msg"></param>
        public static void writeLogInformation(string _str_msg)
        {
            if (!EventLog.SourceExists(CONST_LOG_SOURCE))
            {
                EventLog.CreateEventSource(CONST_LOG_SOURCE, CONST_LOG_SOURCE_NAME);
            }

            using (EventLog myLog = new EventLog())
            {
                myLog.Source = CONST_LOG_SOURCE_NAME;
                myLog.WriteEntry(_str_msg, EventLogEntryType.Information);
            }
        }

        /// <summary>
        /// 写系统日志——警告
        /// </summary>
        /// <param name="_str_msg"></param>
        public static void writeLogWarring(string _str_msg)
        {
            if (!EventLog.SourceExists(CONST_LOG_SOURCE))
            {
                EventLog.CreateEventSource(CONST_LOG_SOURCE, CONST_LOG_SOURCE_NAME);
            }

            using (EventLog myLog = new EventLog())
            {
                myLog.Source = CONST_LOG_SOURCE_NAME;
                myLog.WriteEntry(_str_msg, EventLogEntryType.Warning);
            }
        }

        /// <summary>
        /// 写系统日志——错误
        /// </summary>
        /// <param name="_str_msg"></param>
        public static void writeLogError(string _str_msg)
        {
            if (!EventLog.SourceExists(CONST_LOG_SOURCE))
            {
                EventLog.CreateEventSource(CONST_LOG_SOURCE, CONST_LOG_SOURCE_NAME);
            }
            using (EventLog myLog = new EventLog())
            {
                myLog.Source = CONST_LOG_SOURCE_NAME;
                myLog.WriteEntry(_str_msg, EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// 定义日志源
        /// </summary>
        static private string CONST_LOG_SOURCE = "上汽通用五菱标准采购";
        static private string CONST_LOG_SOURCE_NAME = "上汽通用五菱标准采购程序";
        #endregion

        #region AD认证的相关操作
        /// <summary>
        /// 验证用户，返回已认证的用户类
        /// </summary>
        /// <param name="domain">用户认证的域服务器</param>
        /// <param name="username">用户名</param>
        /// <param name="password">用户密码</param>
        /// <returns>返回通过的验证用户</returns>
        public static AuthenticatedUser ADIdentify(string domain, string username, string password)
        {
            AuthenticatedUser _returnValue = new AuthenticatedUser();

            if (string.IsNullOrEmpty(domain)
                || string.IsNullOrEmpty(username)
                || string.IsNullOrEmpty(password))
            {
                throw new Exception("用户信息不完整，获取用户信息错误！");
            }

            /*获取AD用户的参数名车
    userEntry.Properties["sAMAccountName"].Value	"yuyang"
    userEntry.Properties["name"].Value	"俞阳"
    userEntry.Properties["userPrincipalName"].Value	"yuyang@gxbidding.com"
    userEntry.Properties["displayName"].Value	"俞阳"
    userEntry.Properties["mail"].Value	"yuyang@gxbidding.cn"
    userEntry.Properties["company"].Value	"广西壮族自治区机电设备招标中心"
    userEntry.Properties["department"].Value	"综合部"
    userEntry.Properties["title"].Value	"信息管理员"
    userEntry.Properties["objectGUID"].Value	byte[16]
    userEntry.Properties["mobile"].Value	"18078186878"
    userEntry.Properties["ipPhone"].Value	"18078186878"
             */

            using (var rootEntry = new DirectoryEntry("LDAP://" + domain, username, password, AuthenticationTypes.Secure))
            using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", username)))
            {
                var searchResult = directorySearcher.FindOne();
                if (searchResult != null)
                {
                    #region 能够找到域中相应用户，并获取该用户的基本信息
                    using (var userEntry = searchResult.GetDirectoryEntry())
                    {
                        //获取当前用户的基本信息
                        _returnValue.Name = username;
                        _returnValue.Company = (string)userEntry.Properties["company"].Value;
                        _returnValue.Department = (string)userEntry.Properties["department"].Value;
                        _returnValue.DisplayName = (string)userEntry.Properties["displayName"].Value;
                        _returnValue.ID = (new Guid((byte[])userEntry.Properties["objectGUID"].Value)).ToString("N");
                        _returnValue.IpPhone = (string)userEntry.Properties["ipPhone"].Value;
                        _returnValue.Mail = (string)userEntry.Properties["mail"].Value;
                        _returnValue.Mobile = (string)userEntry.Properties["mobile"].Value;
                        _returnValue.Title = (string)userEntry.Properties["title"].Value;

                        List<string> ADGroups = new List<string>();
                        // Invoke Groups method.
                        object userADGroups = userEntry.Invoke("Groups");
                        foreach (object obj in (IEnumerable)userADGroups)
                        {
                            // Create object for each group.
                            DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj);
                            string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty);
                            groupName = groupName.Replace("CN=", string.Empty);
                            if (ADGroups.IndexOf(groupName) < 0)
                                ADGroups.Add(groupName);
                        }
                        _returnValue.RoleGroups = ADGroups;
                    }
                    #endregion
                }
                else
                {
                    _returnValue.ID = string.Empty;
                }
            }

            return _returnValue;
        }

        /// <summary>
        /// 获取认证的用户
        /// </summary>
        /// <param name="Principal">用户凭证（例如：HttpContext.User）</param>
        /// <returns></returns>
        public static AuthenticatedUser getAuthenticatedUser(System.Security.Principal.IPrincipal Principal)
        {
            var _returnValue = new AuthenticatedUser();

            //从身份验证票中获得用户数据
            string UserData = ((FormsIdentity)Principal.Identity).Ticket.UserData;
            _returnValue = Newtonsoft.Json.JsonConvert.DeserializeObject<AuthenticatedUser>(UserData);

            return _returnValue;
        }
        #endregion

        #region 系统用到的常量定义
        /// <summary>
        /// 定义Session中保存的用户信息的名称
        /// </summary>
        public static readonly string CONST_SESSION_USER = "CONST_SESSION_USER";

        /// <summary>
        /// 传递消息信息的TempData名称
        /// </summary>
        public static readonly string CONST_TEMPDATA_INF = "InformationMessage";

        /// <summary>
        /// 传递消息信息的TempData名称
        /// </summary>
        public static readonly string CONST_TEMPDATA_ERR = "ErrorMessage";

        /// <summary>
        /// 工作流状态-流程等待启动中
        /// </summary>
        public static readonly int CONST_SIMPLEFLOW_STANDBY = 0;

        /// <summary>
        /// 工作流状态-执行中
        /// </summary>
        public static readonly int CONST_SIMPLEFLOW_EXECUTING = 1;

        /// <summary>
        /// 工作流状态-流程批准审批完成
        /// </summary>
        public static readonly int CONST_SIMPLEFLOW_APPROVAL = 99;

        /// <summary>
        /// 工作流状态-流程退回
        /// </summary>
        public static readonly int CONST_SIMPLEFLOW_REFUSE = -1;

        /// <summary>
        /// 工作流邮件审批的链接地址
        /// </summary>
        public static readonly string CONST_URL_MAILTODO = @"https://mail.gxbidding.cn/SimpleFlow/ToDo/ToDoMail";

        /// <summary>
        /// 投标人登录
        /// </summary>
        public static readonly int CONST_LOGIN_ENTERPRISE_BIDDER = 0;

        /// <summary>
        /// 业主登录
        /// </summary>
        public static readonly int CONST_LOGIN_ENTERPRISE_OWNER = 1;

        /// <summary>
        /// 评标专家登录
        /// </summary>
        public static readonly int CONST_LOGIN_EXPERT = 2;

        /// <summary>
        /// 部门内部用户登录
        /// </summary>
        public static readonly int CONST_LOGIN_DEPTARTMENT_USER = 99;

        #region 常量-项目分类
        /// <summary>
        /// 1、国际公开招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_GJGK = "国际公开";

        /// <summary>
        /// 2、国内公开招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_GKZB = "公开招标";

        /// <summary>
        /// 3、邀请招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_YQZB = "邀请招标";

        /// <summary>
        /// 4、竞争性谈判
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_JZXTP = "竞争性谈判";

        /// <summary>
        /// 5、竞争性磋商采购
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_JZXCS = "竞争性磋商采购";

        /// <summary>
        /// 6、单一来源采购
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_DYLY = "单一来源采购";

        /// <summary>
        /// 7、询价采购
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_XJ = "询价采购";

        /// <summary>
        /// 8、其他
        /// </summary>
        public static readonly string CONST_PROJECT_ZBFS_QT = "其他";

        /// <summary>
        /// 1、货物招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBNR_HW = "货物招标";

        /// <summary>
        /// 2、工程招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBNR_GC = "工程招标";

        /// <summary>
        /// 3、服务招标
        /// </summary>
        public static readonly string CONST_PROJECT_ZBNR_FW = "服务招标";
        #endregion

        #region 常量-公告类型
        /// <summary>
        /// 公告常量-项目招标公告【ZBGG】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_ZBGG = "ZBGG";

        /// <summary>
        /// 公告常量-项目变更公告【BGGG】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_BGGG = "BGGG";

        /// <summary>
        /// 公告常量-本网通知【BWTZ】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_BWTZ = "BWTZ";

        /// <summary>
        /// 公告常量-答疑公告【BWTZ】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_DYGG = "DYGG";

        /// <summary>
        /// 公告常量-公司新闻【GSXW】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_GSXW = "GSXW";

        /// <summary>
        /// 公告常量-关于我们【GYWM】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_GYWM = "GYWM";

        /// <summary>
        /// 公告常量-结果公告【JGGG】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_JGGG = "JGGG";

        /// <summary>
        /// 公告常量-控制价发布【JGGS】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_JGGS = "JGGS";

        /// <summary>
        /// 公告常量-结果公示【KZJGG】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_KZJGG = "KZJGG";

        /// <summary>
        /// 公告常量-业务须知【YWXZ】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_YWXZ = "YWXZ";

        /// <summary>
        /// 公告常量-业务指南【YWZN】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_YWZN = "YWZN";

        /// <summary>
        /// 公告常量-招标预告【ZBYG】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_ZBYG = "ZBYG";

        /// <summary>
        /// 公告常量-企业文化【QYWH】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_QYWH = "QYWH";

        /// <summary>
        /// 公告常量-合作企业【HZQY】
        /// </summary>
        public static readonly string CONST_CONTENT_TYPE_HZQY = "HZQY";
        #endregion

        #region 附件类型
        /// <summary>
        /// 附件类型常量-门户发文附件
        /// </summary>
        public static readonly string CONST_ATTACHMENT_TYPE_MHFWFJ = "发文附件";

        /// <summary>
        /// 附件类型常量-门户发文图片
        /// </summary>
        public static readonly string CONST_ATTACHMENT_TYPE_MHFWTP = "发文图片";

        /// <summary>
        /// 附件类型常量-税务登记证扫描件
        /// </summary>
        public static readonly string CONST_ATTACHMENT_TYPE_SM_SWDJ = "税务登记证扫描件";

        /// <summary>
        /// 附件类型常量-营业执照扫描件
        /// </summary>
        public static readonly string CONST_ATTACHMENT_TYPE_SM_YYZZ = "营业执照扫描件";

        /// <summary>
        /// 附件类型常量-组织机构代码证扫描件
        /// </summary>
        public static readonly string CONST_ATTACHMENT_TYPE_SM_ZZJG = "组织机构代码证扫描件";
        #endregion

        #endregion

    }

    #region 用户验证
    /// <summary>
    /// 已验证的用户类
    /// </summary>
    public class AuthenticatedUser
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public string ID { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 显示名
        /// </summary>
        public string DisplayName { get; set; }

        /// <summary>
        /// 用户邮件地址
        /// </summary>
        public string Mail { get; set; }

        /// <summary>
        /// 用户公司
        /// </summary>
        public string Company { get; set; }

        /// <summary>
        /// 用户部门
        /// </summary>
        public string Department { get; set; }

        /// <summary>
        /// 用户职务
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 用户手机
        /// </summary>
        public string Mobile { get; set; }

        /// <summary>
        /// 用户电话
        /// </summary>
        public string IpPhone { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 用户所在角色组
        /// </summary>
        public List<string> RoleGroups { get; set; }

        /// <summary>
        /// 用户是否在角色组中
        /// </summary>
        public bool isUserInGroup(string groupName)
        {
            bool match = false;
            foreach (var group in this.RoleGroups)
            {
                if (group == groupName)
                {
                    match = true;
                    break;
                }
            }

            return match;
        }

        public AuthenticatedUser()
        {
            RoleGroups = new List<string>();
        }
    }

    /// <summary>
    /// AD用户认证的类
    /// </summary>
    public static class ADAuthentication
    {
        /// <summary>
        /// 验证用户，返回已认证的用户类
        /// </summary>
        /// <param name="domain">用户认证的域服务器</param>
        /// <param name="username">用户名</param>
        /// <param name="password">用户密码</param>
        /// <returns>返回通过的验证用户</returns>
        public static AuthenticatedUser identify(string domain, string username, string password)
        {
            AuthenticatedUser _returnValue = new AuthenticatedUser();

            if (string.IsNullOrEmpty(domain)
                || string.IsNullOrEmpty(username)
                || string.IsNullOrEmpty(password))
            {
                throw new Exception("用户信息不完整，获取用户信息错误！");
            }

            /*获取AD用户的参数名车
    userEntry.Properties["sAMAccountName"].Value	"yuyang"
    userEntry.Properties["name"].Value	"俞阳"
    userEntry.Properties["userPrincipalName"].Value	"yuyang@gxbidding.com"
    userEntry.Properties["displayName"].Value	"俞阳"
    userEntry.Properties["mail"].Value	"yuyang@gxbidding.cn"
    userEntry.Properties["company"].Value	"广西壮族自治区机电设备招标中心"
    userEntry.Properties["department"].Value	"综合部"
    userEntry.Properties["title"].Value	"信息管理员"
    userEntry.Properties["objectGUID"].Value	byte[16]
    userEntry.Properties["mobile"].Value	"18078186878"
    userEntry.Properties["ipPhone"].Value	"18078186878"
             */

            using (var rootEntry = new DirectoryEntry("LDAP://" + domain, username, password, AuthenticationTypes.Secure))
            using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", username)))
            {
                var searchResult = directorySearcher.FindOne();
                if (searchResult != null)
                {
                    #region 能够找到域中相应用户，并获取该用户的基本信息
                    using (var userEntry = searchResult.GetDirectoryEntry())
                    {
                        //获取当前用户的基本信息
                        _returnValue.Name = (string)userEntry.Properties["sAMAccountName"].Value;
                        _returnValue.Company = (string)userEntry.Properties["company"].Value;
                        _returnValue.Department = (string)userEntry.Properties["department"].Value;
                        _returnValue.DisplayName = (string)userEntry.Properties["displayName"].Value;
                        _returnValue.ID = (new Guid((byte[])userEntry.Properties["objectGUID"].Value)).ToString("N");
                        _returnValue.IpPhone = (string)userEntry.Properties["ipPhone"].Value;
                        _returnValue.Mail = (string)userEntry.Properties["mail"].Value;
                        _returnValue.Mobile = (string)userEntry.Properties["mobile"].Value;
                        _returnValue.Title = (string)userEntry.Properties["title"].Value;

                        List<string> ADGroups = new List<string>();
                        // Invoke Groups method.
                        object userADGroups = userEntry.Invoke("Groups");
                        foreach (object obj in (IEnumerable)userADGroups)
                        {
                            // Create object for each group.
                            DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj);
                            string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty);
                            groupName = groupName.Replace("CN=", string.Empty);
                            if (ADGroups.IndexOf(groupName) < 0)
                                ADGroups.Add(groupName);
                        }
                        _returnValue.RoleGroups = ADGroups;
                    }
                    #endregion
                }
                else
                {
                    _returnValue.ID = string.Empty;
                }
            }

            return _returnValue;
        }

        /// <summary>
        /// 使用用户名来验证用户
        /// </summary>
        /// <param name="domain">域</param>
        /// <param name="username">用户名</param>
        /// <returns></returns>
        public static AuthenticatedUser identifyFromUserName(string domain, string username)
        {
            AuthenticatedUser _returnValue = new AuthenticatedUser();

            if (string.IsNullOrEmpty(domain)
                || string.IsNullOrEmpty(username))
            {
                throw new Exception("用户信息不完整，获取用户信息错误！");
            }

            /*获取AD用户的参数名车
    userEntry.Properties["sAMAccountName"].Value	"yuyang"
    userEntry.Properties["name"].Value	"俞阳"
    userEntry.Properties["userPrincipalName"].Value	"yuyang@gxbidding.com"
    userEntry.Properties["displayName"].Value	"俞阳"
    userEntry.Properties["mail"].Value	"yuyang@gxbidding.cn"
    userEntry.Properties["company"].Value	"广西壮族自治区机电设备招标中心"
    userEntry.Properties["department"].Value	"综合部"
    userEntry.Properties["title"].Value	"信息管理员"
    userEntry.Properties["objectGUID"].Value	byte[16]
    userEntry.Properties["mobile"].Value	"18078186878"
    userEntry.Properties["ipPhone"].Value	"18078186878"
             */

            using (var rootEntry = new DirectoryEntry("LDAP://" + domain, "led2", "led2", AuthenticationTypes.Secure))
            using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(sAMAccountName={0})", username)))
            {
                var searchResult = directorySearcher.FindOne();
                if (searchResult != null)
                {
                    #region 能够找到域中相应用户，并获取该用户的基本信息
                    using (var userEntry = searchResult.GetDirectoryEntry())
                    {
                        //获取当前用户的基本信息
                        _returnValue.Name = (string)userEntry.Properties["sAMAccountName"].Value;
                        _returnValue.Company = (string)userEntry.Properties["company"].Value;
                        _returnValue.Department = (string)userEntry.Properties["department"].Value;
                        _returnValue.DisplayName = (string)userEntry.Properties["displayName"].Value;
                        _returnValue.ID = (new Guid((byte[])userEntry.Properties["objectGUID"].Value)).ToString("N");
                        _returnValue.IpPhone = (string)userEntry.Properties["ipPhone"].Value;
                        _returnValue.Mail = (string)userEntry.Properties["mail"].Value;
                        _returnValue.Mobile = (string)userEntry.Properties["mobile"].Value;
                        _returnValue.Title = (string)userEntry.Properties["title"].Value;

                        List<string> ADGroups = new List<string>();
                        // Invoke Groups method.
                        object userADGroups = userEntry.Invoke("Groups");
                        foreach (object obj in (IEnumerable)userADGroups)
                        {
                            // Create object for each group.
                            DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj);
                            string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty);
                            groupName = groupName.Replace("CN=", string.Empty);
                            if (ADGroups.IndexOf(groupName) < 0)
                                ADGroups.Add(groupName);
                        }
                        _returnValue.RoleGroups = ADGroups;
                    }
                    #endregion
                }
                else
                {
                    _returnValue.ID = string.Empty;
                }
            }

            return _returnValue;
        }

        /// <summary>
        /// 获取认证的用户
        /// </summary>
        /// <param name="Principal">用户凭证（例如：HttpContext.User）</param>
        /// <returns></returns>
        public static AuthenticatedUser getAuthenticatedUser(System.Security.Principal.IPrincipal Principal)
        {
            var _returnValue = new AuthenticatedUser();

            //从身份验证票中获得用户数据
            string UserData = ((FormsIdentity)Principal.Identity).Ticket.UserData;
            _returnValue = Newtonsoft.Json.JsonConvert.DeserializeObject<AuthenticatedUser>(UserData);

            return _returnValue;
        }

        /// <summary>
        /// 根据组名称，获取用户列表
        /// </summary>
        /// <param name="groupname">组名</param>
        /// <returns></returns>
        public static List<AuthenticatedUser> getUsersForGroup(string domain, string groupname)
        {
            var _returnValue = new List<AuthenticatedUser>();
            if (groupname == string.Empty) return _returnValue;

            using (var rootEntry = new DirectoryEntry("LDAP://" + domain, "led2", "led2", AuthenticationTypes.Secure))
            using (var directorySearcher = new DirectorySearcher(rootEntry, String.Format("(&(objectClass=group)(cn={0}))", groupname)))
            {
                try
                {
                    foreach (SearchResult searchResult in directorySearcher.FindAll())
                    {
                        #region 能够找到域中相应用户，并获取该用户的基本信息
                        using (var userEntry = searchResult.GetDirectoryEntry())
                        {
                            System.DirectoryServices.ResultPropertyCollection pcoll = searchResult.Properties;

                            int n = pcoll["member"].Count;
                            for (int i = 0; i < n; i++)
                            {
                                var lsMemberString = pcoll["member"][i].ToString();
                                DirectoryEntry deUser = new DirectoryEntry("LDAP://" + domain + "/" + lsMemberString, "led2", "led2", AuthenticationTypes.Secure);

                                // Show all users with valid email address
                                if (deUser != null
                                    && deUser.Properties["mail"] != null
                                    && deUser.Properties["mail"].Value != null
                                    && !String.IsNullOrEmpty(deUser.Properties["mail"].Value.ToString()))
                                {
                                    var _u = new AuthenticatedUser()
                                    {
                                        Name = (string)deUser.Properties["sAMAccountName"].Value,
                                        Company = (string)deUser.Properties["company"].Value,
                                        Department = (string)deUser.Properties["department"].Value,
                                        DisplayName = (string)deUser.Properties["displayName"].Value,
                                        ID = (new Guid((byte[])deUser.Properties["objectGUID"].Value)).ToString("N"),
                                        IpPhone = (string)deUser.Properties["ipPhone"].Value,
                                        Mail = (string)deUser.Properties["mail"].Value,
                                        Mobile = (string)deUser.Properties["mobile"].Value,
                                        Title = (string)deUser.Properties["title"].Value
                                    };

                                    _returnValue.Add(_u);

                                    deUser.Close();
                                }
                            }
                        }
                        #endregion
                    }
                    return _returnValue;
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
            }
        }
    }
    #endregion

}